<!DOCTYPE html>
<html>
<head>
    <title>产品查询</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f9;
            margin: 0;
            padding: 20px;
        }
        h1, h2 {
            color: #333;
        }
        .form-inline {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 20px;
        }
        .form-inline label {
            flex: 0 0 auto;
            margin-right: 10px; /* 调整标签和输入框之间的间距 */
        }
        .form-inline input, .form-inline select {
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .form-inline .checkbox-label {
            display: flex;
            align-items: center;
            gap: 5px; /* 控制标签和复选框之间的间距 */
        }
        .form-inline button {
            padding: 8px 16px;
            margin: 0;
            background-color: cornflowerblue;
            color: white;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
            background-color: #fff;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        th, td {
            border: 1px solid #ddd;
            padding: 12px;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
        }
        .product-item {
            border: 1px solid #ddd;
            margin-bottom: 10px;
            padding: 10px;
            background-color: #fff;
            box-shadow: 0 1px 3px rgba(0,0,0,0);
        }
        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 20px;
        }
        .pagination button {
            padding: 8px 16px;
            margin: 0 5px;
            border: none;
            background-color: #007bff;
            color: white;
            border-radius: 4px;
            cursor: pointer;
        }
        .pagination button:disabled {
            background-color: #6c757d;
        }
    </style>
</head>
<body onload="login();">
<h1>产品查询</h1>
<form id="product-search-form" class="form-inline">
    <label for="name">名称：</label>
    <input type="text" id="name" name="name">

    <label for="brand">品牌：</label>
    <input type="text" id="brand" name="brand">

    <label for="category">分类：</label>
    <select id="category" name="category">
        <option value="">请选择分类</option>
        <!-- 分类选项将通过JavaScript动态生成 -->
    </select>

    <label for="lowPrice">最低价：</label>
    <input type="number" id="lowPrice" name="lowPrice">

    <label for="highPrice">最高价：</label>
    <input type="number" id="highPrice" name="highPrice">

    <div class="checkbox-label">
        <label for="unitsInStock">仅包含有货产品：</label>
        <input type="checkbox" id="unitsInStock" name="unitsInStock">
    </div>

    <button type="button" onclick="fetchProducts()">查询</button>
</form>

<h2>产品列表</h2>
<div>
    <table id="products-table">
        <thead>
        <tr>
            <th>ID</th>
            <th>名称</th>
            <th>品牌</th>
            <th>分类</th>
            <th>条码</th>
            <th>单位</th>
            <th>单价</th>
            <th>库存</th>
            <th>已售</th>
        </tr>
        </thead>
        <tbody>
        <!-- 产品列表将在这里动态生成 -->
        </tbody>
    </table>
    <div class="pagination">
        <button onclick="prevPage()" disabled>上一页</button>
        <span id="page-info"></span>
        <button onclick="nextPage()" disabled>下一页</button>
    </div>
</div>

<script>
    let currentPage = 1;
    let totalPage = 0;
    let token = localStorage.getItem('accessToken');

    function login() {
        const loginUrl = '/login';
        const loginData = {
            username: 'test',
            password: 'test'
        };

        fetch(loginUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(loginData)
        })
            .then(response => response.json())
            .then(data => {
                token = data.accessToken;
                localStorage.setItem('accessToken', token);
                console.log('Logged in successfully:', token);
                fetchCategories();
            })
            .catch(error => console.error('Login failed:', error));
    }

    function fetchCategories() {
        const url = '/erp/api/v1/categories/level/1';
        fetch(url, {
            headers: {
                'token': `${token}`
            }
        })
            .then(response => response.json())
            .then(data => {
                const categorySelect = document.getElementById('category');
                data.data.forEach(category => {
                    const option = document.createElement('option');
                    option.value = category.id;
                    option.text = category.name;
                    categorySelect.appendChild(option);
                });
            })
            .catch(error => console.error('Error:', error));
    }

    function fetchProducts() {
        const url = '/erp/api/v1/products';
        const formData = new FormData(document.getElementById('product-search-form'));
        const params = {
            name: formData.get('name'),
            brand: formData.get('brand'),
            categoryId: formData.get('category'),
            lowPrice: formData.get('lowPrice'),
            highPrice: formData.get('highPrice'),
            unitsInStock: formData.get('unitsInStock') === 'on',
            pageNumber: currentPage,
            pageSize: 10
        };

        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'token': `${token}`
            },
            body: JSON.stringify(params)
        })
            .then(response => response.json())
            .then(data => {
                displayProducts(data.data);
                updatePageInfo(data.pageNumber, data.totalPage);
                totalPage = data.totalPage;
                updatePaginationButtons();
            })
            .catch(error => console.error('Error:', error));
    }

    function displayProducts(products) {
        const productsContainer = document.getElementById('products-table').getElementsByTagName('tbody')[0];
        productsContainer.innerHTML = '';

        if (products && products.length > 0) {
            products.forEach(product => {
                const row = productsContainer.insertRow();
                row.insertCell(0).textContent = product.id;
                row.insertCell(1).textContent = product.name;
                row.insertCell(2).textContent = product.brand;
                row.insertCell(3).textContent = product.categoryName;
                row.insertCell(4).textContent = product.barCode;
                row.insertCell(5).textContent = product.quantityPerUnit;
                row.insertCell(6).textContent = product.unitPrice;
                row.insertCell(7).textContent = product.unitsInStock;
                row.insertCell(8).textContent = product.unitsSell;
            });
        } else {
            const row = productsContainer.insertRow();
            const cell = row.insertCell(0);
            cell.colSpan = 9;
            cell.textContent = '暂无产品数据';
        }
    }

    function updatePageInfo(pageNumber, totalPage) {
        const pageInfoSpan = document.getElementById('page-info');
        pageInfoSpan.textContent = `第 ${pageNumber} 页，共 ${totalPage} 页`;
    }

    function updatePaginationButtons() {
        const prevButton = document.querySelector('.pagination button:first-child');
        const nextButton = document.querySelector('.pagination button:last-child');

        if (currentPage > 1) {
            prevButton.disabled = false;
        } else {
            prevButton.disabled = true;
        }

        if (currentPage < totalPage) {
            nextButton.disabled = false;
        } else {
            nextButton.disabled = true;
        }
    }

    function prevPage() {
        if (currentPage > 1) {
            currentPage--;
            fetchProducts();
        }
    }

    function nextPage() {
        if (currentPage < totalPage) {
            currentPage++;
            fetchProducts();
        }
    }
</script>
</body>
</html>